package com.droidclaimcustomer.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.droidclaimcustomer.R;
import com.droidclaimcustomer.bl.CustomerBl;
import com.droidclaimcustomer.bl.DroidClaimBlService;
import com.droidclaimcustomer.dto.ClaimInfoForCustomerResultBlDto;
import com.droidclaimcustomer.dto.ClaimInfoPKBlDto;
import com.droidclaimcustomer.helper.asyntask.ICompleteListener;
import com.droidclaimcustomer.helper.utils.ImageString;
import com.droidclaimcustomer.model.ClaimDetailModel;
import com.droidclaimcustomer.model.ClaimInfoModel;
import com.droidclaimcustomer.model.StatusModel;
import com.droidclaimcustomer.helper.utils.DownloadImage;

public class ClaimDetailActivity extends Activity implements ICompleteListener {
	private final String MAIN_ACTIVITY_REQUEST = "101";
	private final String HISTORY_ACTIVITY_REQUEST = "102";
	private final String GCM_REQUEST = "103";
	private TextView licensePlateNoTV;
	private TextView ownerNameTV;
	private TextView carDetailTV;
	private TextView surveyorNameTV;
	private TextView surveyorIdTV;
	private TextView surveyorMobileTV;
	private TextView statusTV;
	private ImageView surveyorIV;
	private ImageButton callBtn;
	private ImageButton trackLocationBtn;

	private String claimId;
	private String requestId;
	private ClaimDetailModel claimDetail;
	private StatusModel statusModel;
	private String taskGetClaimInfobyClaimIdFormServer;
	private String taskGetlastClaimInfoFormDB;
	private String taskGetClaimInfoByClaimIdFormDB;
	private String downloadTaskId;

	private CustomerBl customerBL;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_claim_detail);
		customerBL = new CustomerBl(this);
		claimDetail = new ClaimDetailModel();
		statusModel = new StatusModel(this);

		// object layout Item
		licensePlateNoTV = (TextView) findViewById(R.id.license_plate_no_textview);
		ownerNameTV = (TextView) findViewById(R.id.owner_name_textview);
		carDetailTV = (TextView) findViewById(R.id.car_detail_textview);
		surveyorNameTV = (TextView) findViewById(R.id.surveyor_name_textview);
		surveyorIdTV = (TextView) findViewById(R.id.surveyor_id_textview);
		surveyorMobileTV = (TextView) findViewById(R.id.surveyor_mobile_textview);
		statusTV = (TextView) findViewById(R.id.status_textview);
		surveyorIV = (ImageView) findViewById(R.id.surveyor_imageview);
		callBtn = (ImageButton) findViewById(R.id.surveyor_call_btn);
		trackLocationBtn = (ImageButton) findViewById(R.id.surveyor_location_btn);

		// set onClickListener
		callBtn.setOnClickListener(onClickDialToSurveyer);
		trackLocationBtn.setOnClickListener(onClickGotoTracking);

	}

	@Override
	protected void onResume() {
		super.onResume();
		// claimInfo model GetIntentExtra
		Bundle extras = getIntent().getExtras();
		// Bundle extras = getParent().getIntent().getExtras();
		if (extras != null) {
			requestId = extras.getString("request_id");
			// requestId = "101";
			// if (extras.getString("request_id") != null) {
			// requestId = extras.getString("request_id");
			// }

			if (requestId.equals(MAIN_ACTIVITY_REQUEST)) {
				/*
				 * from main menu get lasted record form DB get Data by ClaimId
				 */
				taskGetlastClaimInfoFormDB = customerBL
						.GetLastClaimInfo(MainActivity.getLicensePlate());

			} else if (requestId.equals(HISTORY_ACTIVITY_REQUEST)) {
				/* form History activity receive data form getExtra */
				extrasToModel(extras);
				// Clear Request_Id
				// getParent().getIntent().removeExtra("request_id");
				displayClaimDetail();

			} else if (requestId.equals(GCM_REQUEST)) {
				claimId = extras.getString("id");
				if (claimId != null) {
					// check db if empty will get form server
					DroidClaimBlService bl = new DroidClaimBlService(this);
					ClaimInfoPKBlDto cid = new ClaimInfoPKBlDto();
					cid.setId(Integer.parseInt(claimId));
					cid.setSessionId(MainActivity.getSessionId());
					taskGetClaimInfobyClaimIdFormServer = bl
							.GetClaimInfoForCustomer(cid);
				}
			}
		}

		// displayClaimDetail();

	}

	// claim detail form server
	public void dtoToModel(ClaimInfoForCustomerResultBlDto dto) {
		claimDetail.setCarDetail(MainActivity.getCarDetail());
		claimDetail.setOwnerName(MainActivity.getOwnerName());
		claimDetail.setLicensePlateNo(MainActivity.getLicensePlate());
		claimDetail.setSurveyorName(dto.getSurveyorName());
		claimDetail.setSurveyorId(dto.getSurveyorId());
		claimDetail.setSurveyorMobile(dto.getSurveyorMobile());
		claimDetail.setStatus(statusModel.getStatus(dto.getStatus()));

		DownloadImage downloader = new DownloadImage(this);
		downloadTaskId = downloader.load(dto.getSurveyorImg());
//		String strSurveyorImg = dto.getSurveyorImg();
//		if (strSurveyorImg != null) {
//			Bitmap bm = ImageString.toBitmap(strSurveyorImg);
//			claimDetail.setSurveyorImg(bm);
//		}
	}

	// claim detail form Bundle extras
	public void extrasToModel(Bundle extras) {
		claimDetail.setCarDetail(MainActivity.getCarDetail());
		claimDetail.setOwnerName(MainActivity.getOwnerName());
		claimDetail.setLicensePlateNo(MainActivity.getLicensePlate());
		claimDetail.setSurveyorName(extras.getString("surveyorName"));
		claimDetail.setSurveyorId(extras.getString("surveyorId"));
		claimDetail.setSurveyorMobile(extras.getString("mobile"));
		claimDetail.setStatus(String.valueOf(extras.getInt("status")));
		
		String tempSurvImgPath = extras.getString("survImgPath");
		if(tempSurvImgPath != null)
		{
			claimDetail.setSurveyorImg(ImageString.toBitmap(tempSurvImgPath));
		}
	}

	// claim detail form DB
	public void dbToModel(ClaimInfoModel dto) {
		claimDetail.setCarDetail(MainActivity.getCarDetail());
		claimDetail.setOwnerName(MainActivity.getOwnerName());
		claimDetail.setLicensePlateNo(MainActivity.getLicensePlate());
		claimDetail.setSurveyorName(dto.getSurvName());
		claimDetail.setSurveyorId(String.valueOf(dto.getId()));
		claimDetail.setSurveyorMobile(dto.getSurvMobile());
		claimDetail.setStatus(String.valueOf(dto.getStatus()));


		 String strSurveyorImg = dto.getSurvImgPath();
		 if (strSurveyorImg != null) {
		 Bitmap bm = ImageString.toBitmap(strSurveyorImg);
		 claimDetail.setSurveyorImg(bm);
		 }
	}

	// get data from ClaimDetialModel and display view
	public void displayClaimDetail() {

		// Display Claim Detail
		if (claimDetail != null) {
			licensePlateNoTV.setText(claimDetail.getLicensePlateNo());
			ownerNameTV.setText(claimDetail.getOwnerName());
			carDetailTV.setText(claimDetail.getCarDetail());
			surveyorNameTV.setText(claimDetail.getSurveyorName());
			surveyorIdTV.setText(claimDetail.getSurveyorId());
			surveyorMobileTV.setText(claimDetail.getSurveyorMobile());
			if (claimDetail.getStatus() != null) {
				Pattern pattern = Pattern.compile("([0-9]*)");
				if (pattern.matcher(claimDetail.getStatus()).matches()) {
					statusTV.setText(statusModel.getStatus(Integer
							.parseInt(claimDetail.getStatus())));
				} else {
					statusTV.setText(claimDetail.getStatus());
				}
			}

			surveyorIV.setImageBitmap(claimDetail.getSurveyorImg());
		}

		/*
		 * File imgFile = new File(imgPath); if(imgFile.exists()){ Bitmap bmp =
		 * BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		 * surveyorIV.setImageBitmap(bmp); }
		 */

		/*
		 * surveyorImg = dto.getSurveyorImg(); if(surveyorImg != null){ Bitmap
		 * bm = ImageString.toBitmap(surveyorImg);
		 * surveyorIV.setImageBitmap(bm); }else{ Toast.makeText(this,
		 * "Surveyor is null", Toast.LENGTH_LONG).show(); }
		 */
	}

	// public void replaceContentView(String id, Intent newIntent) {
	// View view = getLocalActivityManager().startActivity(id,
	// newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
	// .getDecorView();
	// this.setContentView(view);
	// }

	@Override
	public void onBackPressed() {
		finish();
	}

	public View.OnClickListener onClickGotoTracking = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				// Intent intent = new Intent(ClaimDetailActivity.this,
				// xxx.class);
				// Intent intent = new
				// Intent(ClaimDetailActivity.this,ClaimMapActivity.class);

				Intent intent = new Intent(v.getContext(),
						ClaimMapActivity.class);

				// ActivityStackHistory activityStack = (ActivityStackHistory)
				// getParent();
				// activityStack.push("ClaimMapActivity", intent);
				startActivity(intent);
				// replaceContentView("ClaimDetail", intent);

				// intent.setClass(getBaseContext(),ClaimMapActivity.class);
				// MainActivity.clickTabIndex(3,intent);
			} catch (ActivityNotFoundException activityException) {
				Toast.makeText(ClaimDetailActivity.this, "Error GotoTracting",
						Toast.LENGTH_LONG).show();
			}
		}
	};

	public View.OnClickListener onClickDialToSurveyer = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent.setData(Uri.parse("tel:"
						+ licensePlateNoTV.getText().toString()));
				startActivity(callIntent);
			} catch (ActivityNotFoundException activityException) {
				Toast.makeText(ClaimDetailActivity.this,
						"Error Dial to Surveyer", Toast.LENGTH_LONG).show();
			}
		}
	};

	@Override
	public void onTaskCompleteSuccess(String taskId, Object result) {
		// TODO Auto-generated method stub
		try {
			if (taskId == taskGetClaimInfobyClaimIdFormServer) {
				ClaimInfoForCustomerResultBlDto dto = (ClaimInfoForCustomerResultBlDto) result;
				if (!dto.getLicensePlate().isEmpty()) {

					dtoToModel(dto); // set Model
					/*
					 * get Current Data from DB By ClaimID
					 */
					CustomerBl customerBL = new CustomerBl(this);
					taskGetClaimInfoByClaimIdFormDB = customerBL
							.GetClaimInfoByClaimId(Integer.parseInt(claimId));
					// displayClaimDetail();

				} else {
					Toast.makeText(this, "Error: LicensePlate is null",
							Toast.LENGTH_LONG).show();
				}

			} else if (taskId == taskGetlastClaimInfoFormDB) { // form database

				ArrayList<ClaimInfoModel> valueArray = (ArrayList<ClaimInfoModel>) result;
				if (valueArray != null) {
					ClaimInfoModel dto = (ClaimInfoModel) valueArray.get(0);
					// ClaimInfoModel dto = (ClaimInfoModel) result;
					dbToModel(dto); // set Model

					displayClaimDetail();
				}

			} else if (taskId == taskGetClaimInfoByClaimIdFormDB) {
				// ClaimInfoModel dto = (ClaimInfoModel) result;
				// if (dto != null) {
				// updateClaimInfo(dto); // send current data for update db
				// }
				ArrayList<ClaimInfoModel> valueArray = (ArrayList<ClaimInfoModel>) result;
				if (valueArray != null) {
					ClaimInfoModel dto = (ClaimInfoModel) valueArray.get(0);
					updateClaimInfo(dto);
					dbToModel(dto); // set Model
					displayClaimDetail();
				}
			} else if (taskId.equals(downloadTaskId)) {
				if (result == null) {
					throw new Exception("Error : null image");
				}

				Bitmap suryevorImage = (Bitmap) result;
				claimDetail.setSurveyorImg(suryevorImage);
				claimDetail.setSurveyorImgPath(ImageString.toString(suryevorImage));
				surveyorIV.setImageBitmap(suryevorImage);
			}
		} catch (Exception ex) {
			Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public void updateClaimInfo(ClaimInfoModel dto) {
		CustomerBl customerBL = new CustomerBl(this);
		Date date = new Date();
		ClaimInfoModel claimInfoModel = new ClaimInfoModel();
		claimInfoModel = dto;
		claimInfoModel.setSurvName(claimDetail.getSurveyorName());
		claimInfoModel.setSurvMobile(claimDetail.getSurveyorMobile());
		claimInfoModel.setSurvImg(claimDetail.getSurveyorImg());
		claimInfoModel.setSurvImgPath(claimDetail.getSurveyorImgPath());
		claimInfoModel
				.setStatus(statusModel.getStatus(claimDetail.getStatus()));
		claimInfoModel.setUpdateDate(date);
		boolean isUpdate = customerBL.updateClaiminfo(dto.getRowId(),
				claimInfoModel);

		if (isUpdate) {
			displayClaimDetail();

		} else {
			Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onTaskFailed(String taskId, Exception cause) {
		// TODO Auto-generated method stub
		if (taskId == this.taskGetClaimInfobyClaimIdFormServer
				|| taskId == taskGetlastClaimInfoFormDB) {
			Toast.makeText(this, "Error" + taskId, Toast.LENGTH_LONG).show();
		}

	}

}
